# Create your views here.

import logging
logger = logging.getLogger("django")


# GET / sms_codes / (?P < mobile > 1[3-9]\d{9})
import random

from django_redis import get_redis_connection

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from verifications import constants

# from CMS.libs.yuntongxun.sms import CCP

# Create your views here.

# 获取logger
# logger = logging.getLogger('django')


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    def get(self, request, mobile):
        """
        短信验证码获取:
        1. 随机生成6位数字作为短信验证码内容
        2. 在redis中存储短信验证码真实内容
        3. 使用云通讯给mobile发送短信验证码
        4. 返回应答，短信发送成功
        """
        # 判断60s之内是否给`mobile`发过短信
        redis_conn = get_redis_connection('verify_codes')

        send_flag = redis_conn.get('send_flag_%s' % mobile) # None

        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 1. 随机生成6位数字作为短信验证码内容
        sms_code = '%06d' % random.randint(0, 999999) # 000100
        print(sms_code)

        # 2. 在redis中存储短信验证码真实内容：以sms_<mobile>为key，以验证码内容为value
        # redis_conn.set('<key>', '<value>', '<expires>')
        # redis_conn.setex('<key>', '<expires>', '<value>')

        # 创建redis管道对象
        pl = redis_conn.pipeline()

        # 向管道中添加命令
        pl.setex('sms_%s' % mobile, constants.SMS_CODES_REDIS_EXPIRES, sms_code)
        # 保存短信验证发送标记：设置标记过期时间为60s
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_INTERVAL, 1)

        # 一次性执行管道中所有命令
        pl.execute()

        # 3. 发出发送短信的任务消息
        expires = constants.SMS_CODES_REDIS_EXPIRES // 60

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, expires)

        # 4. 返回应答，短信发送成功
        return Response({'message': 'OK'})




# class SMSCodesView(APIView):
#     def get(self, request, mobile):
#         '''
#         获取短信验证码:
#         1.生成短信验证码内容
#         2.在redis中保存短信验证码内容, 以'mobile'为key, 已短信验证码内容为value
#         3.使用云通讯发送短信验证码
#         4.返回应答, 发送短信成功
#         '''
#
#         # 1.生成短信验证码内容
#         sms_code = "%06d" % random.randint(0, 999999)
#         print(sms_code)
#
#         # 2.在redis中保存短信验证码内容, 以'mobile'为key, 已短信验证码内容为value
#         redis_conn = get_redis_connection("verify_codes")
#
#         redis_conn.setex("sms_%s" % mobile, contents.SMS_CODE_REDIS_EXPIRES, sms_code)
#
#         # 3.使用云通讯发送短信验证码
#         expires = contents.SMS_CODE_REDIS_EXPIRES//60
#
#         try:
#             res = CCP().send_template_sms(mobile, [sms_code, expires], contents.SMS_CODE_TEMP_ID)
#         except Exception as e:
#             logger.error("mobile:%s, 发送短信异常" % mobile)
#             return Response({"message":"发短信验证码异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
#
#         # 发送短信失败：
#         if res != 0:
#             return Response({"message":"发送短信失败"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
#
#         # 4.返回应答, 发送短信成功
#         return Response({"message":"OK"})























